package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class SwitchInheritanceActionExtension extends
		BaseUtiltiyActionExtension {

	protected static final String INHERIT = "javax.persistence.Inheritance";

	protected static final String INHERIT_TYPE = "javax.persistence.InheritanceType";

	private String inheritanceType = null;

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new CleanupEnumerationsAction());
	}

	protected void execute(Class clazz) {
		EList<Generalization> list = clazz.getGeneralizations();
		for (Generalization generalization : list) {
			execute(generalization);
		}
	}

	protected void execute(Generalization generalization) {
		if (ModelUtil.isStereotypeApplied(generalization, INHERIT)) {
			setInheritanceTypeAsString(generalization);
			Console.getStream().println(
					"Set Inheritance Type for: "
							+ ((NamedElement) generalization.getOwner())
									.getQualifiedName() + " to: "
							+ inheritanceType);
		}
	}

	protected void setInheritanceTypeAsString(Element element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, INHERIT);
		Element e = ModelUtil.getProfileElement(element, INHERIT_TYPE);
		if (stereotype != null && e != null) {
			if (e instanceof Enumeration) {
				element.setValue(stereotype, "strategy", ((Enumeration) e)
						.getOwnedLiteral(inheritanceType));
			}
		}
	}

	private class CleanupEnumerationsAction extends BaseUtilityAction {
		private static final String LABEL = "Switch Inheritance Types";

		public CleanupEnumerationsAction() {
			super(LABEL);
		}

		public void run() {
			inheritanceType = openInputDialog("Select Inheritance Type", new String[] { "SINGLE_TABLE",
					"JOINED", "TABLE_PER_CLASS" });
			if (inheritanceType != null && inheritanceType.length() > 0) {
				super.run();
			}
		}
	}
}
